package com.atguigu.msmservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Autowired
    private MsmService msmService;

    //发送验证短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable("phone") String phone){

        String code =  redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotEmpty(code)){
            return R.ok();
        }
//        生成随机4位数
         code = RandomUtil.getFourBitRandom();
        if (StringUtils.isNotEmpty(phone)){
            String subject = "谷粒学院";
            String text = "【谷粒学院】您好，您的登录验证码为：" + code + "，请尽快登录";
            msmService.sendMsg(phone,subject,text);
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return R.ok().message("验证码发送成功");
        }

        return R.error().message("验证码发送异常，请重新发送");
    }

}
